'use strict';

app.controller('adminCtrl', ['$scope','$http','loginService','adminService', function($scope,$http,loginService,adminService){

	
 $scope.init = function() {
	     loginService.islogged();
		 $scope.link = loginService.getLink();
		 loginService.lock_admin(); 
		 $scope.entryLimit = 15;
		 $scope.offset = 0;
		 $scope.disablePrev = true;
		 $scope.disableNext = false;
		 $scope.page_now = 1;
	     $scope.list_admins();
	    };
	
$scope.del = function(userid){
       
      
		   var uid = loginService.getUser(); 
		   
           adminService.delete_admin(uid.username,uid.password,userid);		   
          			 
   		//   $http.get($scope.link+'admin/del/'+uid.username+'/'+uid.password+'/'+userid).success(function(data){
			//        	console.log('user is deleted');
				//		$location.path('/home');
			     //   }).error(function(data, status, config) {
			      //  	console.log('can not delete this admin with id : ' + userid);
				//		alert('can not delete admin');
			     //  });   
		  
		  //$scope.getUserById(userid,1);
		  //$scope.go(userid,0,1);  
		 
	 }
	
	
	 $scope.currentPage = 1; //current page
	 
	  //=====================paging list member of groups======================
	    $scope.entryLimit_group = 2
	    $scope.offset_group = 0;
	    $scope.disablePrev_group = true;
	    $scope.disableNext_group = false;
	    $scope.page_now_group = 1;
	    //================================================================
	 
	    //=====================paging list groups of user======================
	    $scope.entryLimit_group_ = 5;
	    $scope.offset_group_ = 0;
	    $scope.disablePrev_group_ = true;
	    $scope.disableNext_group_ = false;
	    $scope.page_now_group_ = 1;
	    //================================================================
	 
	 var show_list_group = 1;
	 var show_group_detail = 0;
	 var show_user_detail = 0;
	 
	  $scope.list_group_visible = function (id) {
		    return show_list_group == id;
	 };  
	 
	 
	  $scope.group_detail_visible = function (id) {
	        return show_group_detail == id;
	  };  
	 
	  
	  $scope.return_group_detail = function(user,id) {
		  if ( $scope.type_return ==1){
			show_list_group = 1;
			show_group_detail = 0;    
		  }
		  else if ( $scope.type_return ==2){
			  show_user_detail = 1;
			  show_group_detail = 0;
			  show_list_group = 0;
			  $scope.type_return = 1;
			  $scope.go_user_detail($scope.user_id,1);
		  }
		};
	  
		
		$scope.return_ = function(user,id) {
			if ( $scope.type_return ==1){
				show_user_detail = 0;
				show_group_detail = 1;
			    $scope.list_admins();
			}
			
			else if ( $scope.type_return ==2){
				//show = 1;
				show_group_detail = 1;	
				show_user_detail = 0;
				$scope.type_return = 1;
			}
			
		};	
	  

		// switch to next page
		$scope.nextPage_group = function() { 
	       nextPage_common_group($scope);
		}

		// switch to previous page
		$scope.previousPage_group = function() {
	      previousPage_common_group($scope);
		}
		
		
		// switch to next page
		$scope.nextPage_group_ = function() { 
	       nextPage_common_group_($scope);
		}

		// switch to previous page
		$scope.previousPage_group_ = function() {
	      previousPage_common_group_($scope);
		}
		
		
		
	
		
		
		
		$scope.filter_group = function () { 
			$scope.filtered_search = null;
			$scope.filtered_search = angular.copy($scope.filtered);
			if($scope.nb_row_notchange == $scope.filtered.length)
			   $scope.filtered_ini = angular.copy($scope.filtered);
		 
			if( !angular.isUndefined($scope.search1) ) { 
			
				if( !angular.isUndefined($scope.filtered_ini) )  { 
					$scope.recalculate_array($scope.filtered_ini);
					$scope.disablePrev = true;
				}
				$scope.filter_ini = $scope.filtered.length;
			}
			
         }	
		
		
		$scope.$watch('b', function() {   
			if( ($scope.page_now_group==1)  &&  ($scope.nbr_rows_groups <= $scope.entryLimit_group) )
			 {
			 $scope.disableNext_group = true;
			 }
			
		}); 
		
		$scope.$watch('c', function() {   
			if( ($scope.page_now_group_==1)  &&  ($scope.nbr_rows_members <= $scope.entryLimit_group_) )
			 {
			 $scope.disableNext_group_ = true;
			 }
			
		}); 
		
		  $scope.$watch('filtered', function() {
			  if( !angular.isUndefined($scope.search1) ) { 
					$scope.filter_ini = $scope.filtered.length;
				}
			  
			  if($scope.search1 ==''){  
					$scope.filter_ini = $scope.nb_row_notchange;
				}
			  
		
			 if( ($scope.page_now==1)  &&  ($scope.filter_ini <= $scope.entryLimit) )
				 { 
					 if(!angular.isUndefined($scope.search1)){  //search has some thing
					    if(!$scope.click_prev)
					    	$scope.disableNext = true;
					}
//					 if($scope.filter_ini <= $scope.entryLimit)
//						 $scope.disableNext = true;
				 }
 			 else if(($scope.page_now==1) &&  ($scope.filter_ini > $scope.entryLimit)){
 				  
				   $scope.disableNext = false; 
 				
			 }
			 

				 if( ($scope.page_now==$scope.noOfPages)  &&  ($scope.filter_ini <= $scope.entryLimit) )
		 				$scope.disablePrev = true;
			     else if(($scope.page_now==$scope.noOfPages) &&  ($scope.filter_ini > $scope.entryLimit)){
						 $scope.disablePrev = false;
			     }

			 
				 
			 if(($scope.page_now!=1) && ($scope.page_now!=$scope.noOfPages)){ 
			    if ( $scope.filter_ini < $scope.entryLimit){ //alert($scope.filter_ini);
					 $scope.disableNext = true;
                     //$scope.disablePrev = true;
				 }
				 else{
					 $scope.disableNext = false;
					 //$scope.disablePrev = false;
				 }
			 }
			 
		   });
		
	
		 $scope.list_admins = function(){
			 $http.get($scope.link+'admins').success(function(data,status, config){
					console.log('load list of admins');
					$scope.model = data;
					$scope.jsonToArray(data);
					//pageResult($scope);
                         			
					$scope.nb_row_notchange =  data.data.length;
					$scope.noOfPages = Math.ceil($scope.nb_row_notchange/$scope.entryLimit);
					
				})
				.error(function(data, status, config) {
					console.log('can not load list of admins');
			    });
		 }
		
		 
		 $scope.lock = function(groupid,id){
			  if(id==0){
				  $http.get($scope.link+'group_bl/'+groupid).success(function(data){
				        	console.log('group is locked');
				         }).error(function(data, status, config) {
				        	console.log('can not lock group with id : ' + groupid);
				       });
				 
				  
				 
			  }
			  else if(id==1){
				  $http.get($scope.link+'group_ubl/'+groupid).success(function(data){
			        	console.log('group is unlocked');
			        	$scope.unlock = data;
			        	$scope.list_admins();
			         }).error(function(data, status, config) {
			        	console.log('can not un lock group with id : ' + groupid);
			       });  
			  }
			  
			  $scope.getGroupByGroupId(groupid);
			  $scope.group_go(groupid,0,1);  
			 
		 }
	 
		
	  
	  $scope.jsonToArray = function (data) { //alert(JSON.stringify( data));
			$scope.a = new Array();
			var i = 0;
			angular.forEach(data.data,function(){
				$scope.a[i]=new Array(4);
				$scope.a[i][0] =  data.data[i].id;
	    		$scope.a[i][1] =  data.data[i].firstname;
	    		$scope.a[i][2] =  data.data[i].lastname;
				$scope.a[i][3] =  data.data[i].status;
//				$scope.a[i][3] =  data.data[i].description;
//				$scope.a[i][4] =  data.data[i].location;
//				//$scope.a[i][4] =  data.data[i].address;
//				$scope.a[i][5] =  data.data[i].searchable;
//				$scope.a[i][6] =  data.data[i].owner_id;
//				$scope.a[i][7] =  data.data[i].privacy;
	            i++;
	        })
	        $scope.nbr_rows = i ;
			$scope.filter_ini = i ;
			$scope.a_ini= angular.copy($scope.a);
			//alert('truoc ' + $scope.a[0][7]);
		}
	  
	  
	  
	  $scope.recalculate_array = function (data) { 
			 $scope.a = new Array();
			 var i = 0;
			 angular.forEach(data,function(){
				 $scope.a[i]=new Array(8);
				 var splitted =  ((data[i]).toString()).split(',') ;
				// alert(splitted[0]);
			      $scope.a[i][0] =  splitted[0];
			      $scope.a[i][1] =  splitted[1];
				  $scope.a[i][2] =  splitted[2];
//				  $scope.a[i][3] =  splitted[3];
//				  $scope.a[i][4] =  splitted[4];
//				  $scope.a[i][5] =  splitted[5];
//				  $scope.a[i][6] =  splitted[6];  //alert(splitted[6]);
//				  $scope.a[i][7] =  splitted[7];
				 // $scope.a[i][8] =  splitted[8];
				 i++;

	         })
	         $scope.nbr_rows = i ;
			 $scope.a_ini= angular.copy($scope.a);
		 }
	  
	  
	  $scope.nextPage = function() {
		  nextPage_group($scope);
	  }
	  
	  $scope.previousPage = function() {
		  previousPage_group($scope);
	  }
	 
	  
		$scope.group_go = function(groupId, id, type_return,userId) { 
			show_group_detail = 1;
			show_list_group = 0;
			show_user_detail = 0;
		    $scope.getGroupByGroupId(groupId);
		    $scope.type_return = type_return;
		    $scope.user_id = userId;
		};
	  
		$scope.group_go_user = function(user,id) {
			show_group_detail = id;
			show_list_group = 0;
		    $scope.getUserById_group(user);
		    
		};
		
		 $scope.getGroupByGroupId = function(id){
		        $http.get($scope.link+'group/'+id).success(function(data){
		        	console.log('a group is loaded');
		        	$scope.group = data;
		        	$scope.getUserById_group(data.data.owner_id);
		        	
		        	var loc = data.data.location;
		        	var loc_Str = loc.toString();
		        	var arr  = loc_Str.split(",") ; 
		        	$scope.long = arr[0];
		        	$scope.lat = arr[1];
		        	
		        	$scope.getUsersByGroupId(id);
		        	
		        }).error(function(data, status, config) {
		        	console.log('can not load group with group id : ' + id);
		 });
		 }
		 
		 
		 $scope.getUserById_group = function(id){
		        $http.get($scope.link+'users/'+id).success(function(data){
		        	console.log('owner is loaded');
		        	$scope.owner = data;
		        	//alert(data.data.id);
		        	 $scope.getGroupsByUserId(data.data.id);
		        }).error(function(data, status, config) {
		        	console.log('can not load owner with id : ' + id);
		 });
		 }
		 
		 
		 $scope.getUsersByGroupId = function(id){
		        $http.get($scope.link+'user_group/'+id).success(function(data){
		        	console.log('list users by group is loaded');
		        	$scope.lst_user = data;
		        	$scope.nb_users = data.data.members_list.length;
		        	$scope.jsonToArray_members(data);
		        	pageResult_group($scope);
		        }).error(function(data, status, config) {
		        	console.log('can not load list of users by group Id : ' + id);
		 });
		 }
		 
		 $scope.jsonToArray_members = function (data) {
				$scope.b = new Array();
				var i = 0;
				angular.forEach(data.data.members_list,function(){
					$scope.b[i]=new Array(2);
		    		$scope.b[i][0] =  data.data.members_list[i].name;
					$scope.b[i][1] =  data.data.members_list[i].id;
		            i++;
		        })
		        $scope.nbr_rows_groups = i ;
				
				$scope.b_ini= angular.copy($scope.b);
			}
		 
		 $scope.jsonToArray_groups = function (data) {
				$scope.c = new Array();
				var i = 0;
				angular.forEach(data.data.groups_list,function(){
					$scope.c[i]=new Array(2);
		    		$scope.c[i][0] =  data.data.groups_list[i].name;
					$scope.c[i][1] =  data.data.groups_list[i].id;
		            i++;
		        })
		        $scope.nbr_rows_members = i ;
				
				$scope.c_ini= angular.copy($scope.c);
			}
		 
		 
		 $scope.go_user_detail = function(user,id) {
               show_list_group = 0;
			   show_group_detail = 0;
			   show_user_detail = 1;
			   $scope.getUserById_group(user);
			  // alert(JSON.stringify($scope.owner));
			    
			};
			
		
			
		
		 $scope.is = function (id) {
			  return show_user_detail == id;
		 };
		 
		 $scope.getGroupsByUserId = function(id){
		        $http.get($scope.link+'groups/'+id).success(function(data){
		        	console.log('groups is loaded');
		        	$scope.groups = data;
		        	$scope.jsonToArray_groups(data);
		        	pageResult_group_($scope);
		        }).error(function(data, status, config) {
		        	console.log('can not load list of groups with user id : ' + id);
		 });
		 }
		 
		 $scope.lock = function(userid,id){
			  if(id==0){
				
				
					  $http.get($scope.link+'user_bl/'+userid).success(function(data){
				        	console.log('user is locked');
				          }).error(function(data, status, config) {
				        	console.log('can not lock user with id : ' + userid);
				       });
				 
				  
				 
			  }
			  else if(id==1){
				  $http.get($scope.link+'user_ubl/'+userid).success(function(data){
			        	console.log('user is unlocked');
			        	$scope.unlock = data;
			         }).error(function(data, status, config) {
			        	console.log('can not un lock user with id : ' + userid);
			       });  
			  }
			  
			  $scope.getUserById_group(userid);
			  $scope.go_user_detail(userid,1)
			 
		 }

	
	
	
}])